import React, { useState, useRef, useEffect } from "react";
import {
  Card,
  Input,
  Button,
  Space,
  Avatar,
  Typography,
  List,
  Spin,
  message,
  Tag,
  Divider,
  Tooltip,
  Modal,
  Progress,
  Tabs,
  Row,
  Col,
  Badge,
  Rate,
  Alert,
  Select,
} from "antd";
import {
  SendOutlined,
  RobotOutlined,
  UserOutlined,
  ClearOutlined,
  QuestionCircleOutlined,
  BulbOutlined,
  BookOutlined,
  CopyOutlined,
  StarOutlined,
  BulbOutlined as LightbulbOutlined,
  TagOutlined as TargetOutlined,
  ClockCircleOutlined,
  CheckCircleOutlined,
  WarningOutlined,
  FileTextOutlined,
  CodeOutlined,
  CalculatorOutlined,
  ExperimentOutlined,
  SoundOutlined,
  HeartOutlined,
  DownloadOutlined,
  ShareAltOutlined,
  EyeOutlined,
  ThunderboltOutlined,
} from "@ant-design/icons";
import { useUser } from "../../contexts/UserContext";
import { aiAPI } from "../../services/api";
import styled from "styled-components";

const { TextArea } = Input;
const { Text, Paragraph } = Typography;
const { TabPane } = Tabs;
const { Option } = Select;

interface ChatMessage {
  id: string;
  type: "user" | "ai";
  content: string;
  timestamp: Date;
  isTyping?: boolean;
  rating?: number;
  helpful?: boolean;
  category?: string;
  attachments?: Array<{
    type: "code" | "formula" | "diagram" | "link";
    content: string;
    title: string;
  }>;
}

interface LearningPath {
  id: string;
  title: string;
  description: string;
  progress: number;
  difficulty: "beginner" | "intermediate" | "advanced";
  estimatedTime: string;
  steps: Array<{
    title: string;
    completed: boolean;
    resources: string[];
  }>;
}

interface StudyTip {
  id: string;
  category: string;
  title: string;
  description: string;
  difficulty: string;
  usefulness: number;
}

const ChatContainer = styled.div`
  height: 700px;
  display: flex;
  flex-direction: column;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
  overflow: hidden;
`;

const ChatHeader = styled.div`
  padding: 20px 24px;
  background: linear-gradient(135deg, #1890ff 0%, #40a9ff 50%, #69c0ff 100%);
  color: white;
  display: flex;
  align-items: center;
  justify-content: space-between;
  position: relative;

  &::after {
    content: "";
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    height: 3px;
    background: linear-gradient(
      90deg,
      #ff4d4f,
      #faad14,
      #52c41a,
      #1890ff,
      #722ed1
    );
    opacity: 0.8;
  }
`;

const AIStatus = styled.div`
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;

  .status-dot {
    width: 8px;
    height: 8px;
    background: #52c41a;
    border-radius: 50%;
    animation: pulse 2s infinite;
  }

  @keyframes pulse {
    0% {
      opacity: 1;
    }
    50% {
      opacity: 0.5;
    }
    100% {
      opacity: 1;
    }
  }
`;

const ChatMessages = styled.div`
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  background: linear-gradient(135deg, #f0f8ff 0%, #f9f9f9 100%);

  &::-webkit-scrollbar {
    width: 8px;
  }

  &::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 4px;
  }

  &::-webkit-scrollbar-thumb {
    background: #c1c1c1;
    border-radius: 4px;

    &:hover {
      background: #a8a8a8;
    }
  }
`;

const MessageItem = styled.div<{ isUser: boolean }>`
  display: flex;
  margin-bottom: 20px;
  justify-content: ${(props) => (props.isUser ? "flex-end" : "flex-start")};
  align-items: flex-start;
  gap: 12px;
`;

const MessageBubble = styled.div<{ isUser: boolean }>`
  max-width: 75%;
  padding: 16px 20px;
  border-radius: 20px;
  background: ${(props) =>
    props.isUser
      ? "linear-gradient(135deg, #1890ff 0%, #40a9ff 100%)"
      : "#fff"};
  color: ${(props) => (props.isUser ? "#fff" : "#333")};
  box-shadow: 0 3px 12px rgba(0, 0, 0, 0.15);
  position: relative;
  border: ${(props) => (props.isUser ? "none" : "1px solid #e8e8e8")};

  .message-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 8px;
    font-size: 12px;
    opacity: 0.8;
  }

  .message-content {
    line-height: 1.6;
    word-break: break-word;

    pre {
      background: rgba(0, 0, 0, 0.05);
      padding: 12px;
      border-radius: 8px;
      margin: 8px 0;
      font-family: "Courier New", monospace;
      overflow-x: auto;
    }

    code {
      background: rgba(0, 0, 0, 0.1);
      padding: 2px 6px;
      border-radius: 4px;
      font-family: "Courier New", monospace;
    }
  }

  .message-actions {
    margin-top: 12px;
    display: flex;
    gap: 8px;
    opacity: 0.7;

    .action-btn {
      background: none;
      border: none;
      color: ${(props) => (props.isUser ? "#fff" : "#666")};
      cursor: pointer;
      padding: 4px;
      border-radius: 4px;
      transition: all 0.2s;

      &:hover {
        background: rgba(0, 0, 0, 0.1);
        opacity: 1;
      }
    }
  }
`;

const MessageAvatar = styled(Avatar)<{ isUser: boolean }>`
  background: ${(props) =>
    props.isUser
      ? "linear-gradient(135deg, #1890ff, #40a9ff)"
      : "linear-gradient(135deg, #52c41a, #73d13d)"};
  border: 2px solid #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
`;

const ChatInput = styled.div`
  padding: 20px 24px;
  border-top: 1px solid #f0f0f0;
  background: white;
`;

const QuickActions = styled.div`
  display: flex;
  gap: 8px;
  margin-bottom: 16px;
  flex-wrap: wrap;
`;

const QuickButton = styled(Button)`
  border-radius: 16px;
  height: 32px;
  font-size: 12px;
  border: 1px solid #d9d9d9;
  background: linear-gradient(135deg, #fafafa, #fff);
  color: #666;
  transition: all 0.3s;

  &:hover {
    border-color: #1890ff;
    color: #1890ff;
    background: linear-gradient(135deg, #e6f7ff, #f0f8ff);
    transform: translateY(-1px);
  }

  .anticon {
    margin-right: 4px;
  }
`;

const TypingIndicator = styled.div`
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px 20px;
  margin-bottom: 16px;

  .dots {
    display: flex;
    gap: 6px;

    span {
      width: 6px;
      height: 6px;
      background: #1890ff;
      border-radius: 50%;
      animation: typing 1.5s infinite;

      &:nth-child(2) {
        animation-delay: 0.2s;
      }

      &:nth-child(3) {
        animation-delay: 0.4s;
      }
    }
  }

  @keyframes typing {
    0%,
    60%,
    100% {
      transform: translateY(0);
      opacity: 0.4;
    }
    30% {
      transform: translateY(-8px);
      opacity: 1;
    }
  }
`;

const SidePanel = styled.div`
  width: 300px;
  border-left: 1px solid #f0f0f0;
  background: #fafafa;
  display: flex;
  flex-direction: column;
`;

const LearningPathCard = styled(Card)`
  margin: 8px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

  .ant-card-body {
    padding: 16px;
  }

  .path-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 8px;
  }

  .difficulty-tag {
    font-size: 10px;
    padding: 2px 6px;
    border-radius: 8px;
  }
`;

const AIChat: React.FC = () => {
  const { user } = useUser();
  const [messages, setMessages] = useState<ChatMessage[]>([
    {
      id: "welcome",
      type: "ai",
      content: `🎓 你好${user?.name || "同学"}！我是你的AI学习助手小智，具备以下能力：\n\n📚 **课程答疑**：解答各科目疑难问题\n🧭 **学习规划**：制定个性化学习路径\n💡 **方法指导**：分享高效学习技巧\n🔧 **代码调试**：帮助解决编程问题\n📊 **知识梳理**：整理重点难点\n\n有任何学习问题都可以问我哦！让我们一起让学习变得更高效、更有趣！✨`,
      timestamp: new Date(),
      category: "greeting",
    },
  ]);
  const [inputValue, setInputValue] = useState("");
  const [isLoading, setIsLoading] = useState(false);
  const [isTyping, setIsTyping] = useState(false);
  const [activeTab, setActiveTab] = useState("chat");
  const [selectedCategory, setSelectedCategory] = useState("all");
  const [showSuggestions, setShowSuggestions] = useState(true);
  const messagesEndRef = useRef<HTMLDivElement>(null);
  const inputRef = useRef<HTMLTextAreaElement>(null);

  // 学习路径数据
  const [learningPaths] = useState<LearningPath[]>([
    {
      id: "os-fundamentals",
      title: "操作系统基础",
      description: "从零开始掌握操作系统核心概念",
      progress: 65,
      difficulty: "intermediate",
      estimatedTime: "4-6周",
      steps: [
        { title: "进程与线程", completed: true, resources: ["视频", "练习题"] },
        { title: "内存管理", completed: true, resources: ["文档", "实验"] },
        { title: "文件系统", completed: false, resources: ["视频", "作业"] },
        { title: "设备管理", completed: false, resources: ["文档"] },
      ],
    },
    {
      id: "data-structures",
      title: "数据结构精通",
      description: "深入理解各种数据结构及应用",
      progress: 40,
      difficulty: "intermediate",
      estimatedTime: "6-8周",
      steps: [
        { title: "线性数据结构", completed: true, resources: ["视频", "代码"] },
        {
          title: "树形数据结构",
          completed: false,
          resources: ["练习", "实战"],
        },
        { title: "图数据结构", completed: false, resources: ["算法", "项目"] },
      ],
    },
  ]);

  // 学习建议数据
  const [studyTips] = useState<StudyTip[]>([
    {
      id: "pomodoro",
      category: "时间管理",
      title: "番茄工作法",
      description: "25分钟专注学习 + 5分钟休息，提高学习效率",
      difficulty: "简单",
      usefulness: 4.8,
    },
    {
      id: "feynman",
      category: "理解方法",
      title: "费曼学习法",
      description: "用简单语言解释复杂概念，检验理解程度",
      difficulty: "中等",
      usefulness: 4.9,
    },
    {
      id: "spaced-repetition",
      category: "记忆技巧",
      title: "间隔重复",
      description: "根据遗忘曲线安排复习时间，巩固长期记忆",
      difficulty: "中等",
      usefulness: 4.7,
    },
  ]);

  const quickQuestions = [
    {
      text: "如何学习操作系统？",
      icon: <BookOutlined />,
      category: "学习方法",
    },
    {
      text: "进程和线程的区别",
      icon: <QuestionCircleOutlined />,
      category: "技术问题",
    },
    { text: "数据结构学习建议", icon: <BulbOutlined />, category: "学习规划" },
    { text: "算法复杂度分析", icon: <CalculatorOutlined />, category: "算法" },
    { text: "如何调试程序？", icon: <CodeOutlined />, category: "编程技巧" },
    { text: "制定学习计划", icon: <TargetOutlined />, category: "学习规划" },
    {
      text: "提高编程能力",
      icon: <ThunderboltOutlined />,
      category: "技能提升",
    },
    {
      text: "计算机网络基础",
      icon: <ExperimentOutlined />,
      category: "基础知识",
    },
  ];

  useEffect(() => {
    scrollToBottom();
  }, [messages, isTyping]);

  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
  };

  const generateAIResponse = (userMessage: string): string => {
    const lowerMessage = userMessage.toLowerCase();

    // 基于关键词生成响应
    if (lowerMessage.includes("操作系统") || lowerMessage.includes("os")) {
      return `📚 **操作系统学习建议**：\n\n**理论基础**：\n• 进程和线程概念及区别\n• 内存管理机制（虚拟内存、分页等）\n• 文件系统结构\n• 同步与互斥\n\n**实践方法**：\n• 通过模拟器理解CPU调度\n• 编写简单的内存分配程序\n• 学习Linux系统调用\n\n**推荐资源**：\n• 《操作系统概念》教材\n• xv6操作系统源码\n• 在线模拟器练习\n\n💡 建议先掌握基本概念，再通过编程实践加深理解！`;
    }

    if (lowerMessage.includes("进程") && lowerMessage.includes("线程")) {
      return `🔍 **进程 vs 线程**：\n\n**进程（Process）**：\n• 独立的内存空间\n• 包含代码、数据、堆栈\n• 进程间通信成本高\n• 创建销毁开销大\n\n**线程（Thread）**：\n• 共享进程内存空间\n• 只有独立的栈和寄存器\n• 线程间通信简单\n• 创建销毁开销小\n\n**形象比喻**：\n进程像独立的房子，线程像房子里的房间。房间共享厨房、客厅等公共空间，但有自己的私人物品。\n\n💻 **代码示例**：\n\`\`\`python\n# 多进程\nfrom multiprocessing import Process\n\n# 多线程  \nfrom threading import Thread\n\`\`\``;
    }

    if (lowerMessage.includes("数据结构") || lowerMessage.includes("算法")) {
      return `🏗️ **数据结构学习路径**：\n\n**第一阶段：线性结构**\n• 数组、链表、栈、队列\n• 掌握基本操作和应用场景\n\n**第二阶段：树形结构**\n• 二叉树、二叉搜索树、平衡树\n• 堆、哈夫曼树\n\n**第三阶段：图结构**\n• 图的表示方法\n• 深度优先、广度优先遍历\n• 最短路径算法\n\n**学习方法**：\n🎯 每种数据结构都要：\n1. 理解基本概念和特性\n2. 手写基本操作代码\n3. 解决相关算法题目\n4. 分析时间空间复杂度\n\n💡 推荐先画图理解，再编码实现！`;
    }

    if (lowerMessage.includes("学习计划") || lowerMessage.includes("规划")) {
      return `📅 **制定高效学习计划**：\n\n**SMART原则**：\n• **S**pecific：目标具体明确\n• **M**easurable：可衡量进度\n• **A**chievable：目标可实现\n• **R**elevant：与目标相关\n• **T**ime-bound：有时间限制\n\n**建议步骤**：\n1️⃣ **评估现状**：了解当前知识水平\n2️⃣ **设定目标**：短期（1周）+ 中期（1月）+ 长期（1学期）\n3️⃣ **分解任务**：将大目标分解为小任务\n4️⃣ **时间分配**：合理安排学习时间\n5️⃣ **定期回顾**：每周检查进度并调整\n\n⏰ **时间管理技巧**：\n• 番茄工作法（25分钟专注）\n• 艾森豪威尔矩阵（重要性分类）\n• 时间记录法（了解时间去向）`;
    }

    if (
      lowerMessage.includes("编程") ||
      lowerMessage.includes("代码") ||
      lowerMessage.includes("调试")
    ) {
      return `💻 **编程能力提升指南**：\n\n**基础能力**：\n• 熟练掌握一门主力语言\n• 理解基本语法和数据类型\n• 掌握流程控制结构\n\n**核心技能**：\n🧩 **问题分解**：将复杂问题拆分为小问题\n🔧 **算法思维**：选择合适的算法和数据结构\n🐛 **调试技巧**：\n  - 使用调试器逐步执行\n  - 添加打印语句跟踪变量\n  - 橡皮鸭调试法（向别人解释代码）\n\n**实践建议**：\n• 每日编程练习（LeetCode、牛客等）\n• 参与开源项目\n• 编写技术博客总结\n• Code Review 他人代码\n\n🚀 **进阶路径**：\n算法竞赛 → 项目实战 → 系统设计 → 架构思维`;
    }

    if (lowerMessage.includes("网络") || lowerMessage.includes("计算机网络")) {
      return `🌐 **计算机网络学习要点**：\n\n**OSI七层模型**：\n• 物理层：比特传输\n• 数据链路层：帧传输、错误检测\n• 网络层：路由选择（IP协议）\n• 传输层：端到端通信（TCP/UDP）\n• 会话层：建立、管理、终止会话\n• 表示层：数据加密、压缩\n• 应用层：用户接口（HTTP、FTP等）\n\n**重点协议**：\n🔗 **TCP**：可靠传输、三次握手、四次挥手\n📦 **UDP**：无连接、高效率\n🌍 **HTTP/HTTPS**：Web通信协议\n📧 **DNS**：域名解析\n\n**学习方法**：\n• 使用Wireshark抓包分析\n• 搭建简单网络实验环境\n• 理论与实践相结合`;
    }

    // 默认响应
    return `🤔 这是一个很好的问题！让我来帮你分析一下：\n\n${userMessage}\n\n**我的建议**：\n• 先明确问题的核心要点\n• 查阅相关的理论知识\n• 通过实践加深理解\n• 与同学讨论交流\n\n如果需要更详细的解答，请告诉我具体的困惑点，我会为你提供更有针对性的帮助！💪\n\n💡 **小贴士**：学习是一个循序渐进的过程，保持耐心和持续的练习是关键！`;
  };

  const sendMessage = async (content: string) => {
    if (!content.trim()) return;

    const userMessage: ChatMessage = {
      id: Date.now().toString(),
      type: "user",
      content: content.trim(),
      timestamp: new Date(),
    };

    setMessages((prev) => [...prev, userMessage]);
    setInputValue("");
    setIsTyping(true);
    setShowSuggestions(false);

    // 模拟AI思考时间
    setTimeout(
      () => {
        const aiResponse: ChatMessage = {
          id: (Date.now() + 1).toString(),
          type: "ai",
          content: generateAIResponse(content),
          timestamp: new Date(),
          category: "response",
        };

        setMessages((prev) => [...prev, aiResponse]);
        setIsTyping(false);
      },
      1500 + Math.random() * 1000
    );
  };

  const handleQuickQuestion = (question: string) => {
    sendMessage(question);
  };

  const clearChat = () => {
    Modal.confirm({
      title: "清空聊天记录",
      content: "确定要清空所有聊天记录吗？",
      onOk: () => {
        setMessages([messages[0]]); // 保留欢迎消息
        setShowSuggestions(true);
        message.success("聊天记录已清空");
      },
    });
  };

  const copyMessage = (content: string) => {
    navigator.clipboard.writeText(content);
    message.success("内容已复制到剪贴板");
  };

  const rateMessage = (messageId: string, rating: number) => {
    setMessages((prev) =>
      prev.map((msg) => (msg.id === messageId ? { ...msg, rating } : msg))
    );
    message.success("感谢您的反馈！");
  };

  const handleKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === "Enter" && !e.shiftKey) {
      e.preventDefault();
      sendMessage(inputValue);
    }
  };

  const filteredTips =
    selectedCategory === "all"
      ? studyTips
      : studyTips.filter((tip) => tip.category === selectedCategory);

  const renderMessage = (message: ChatMessage) => (
    <MessageItem key={message.id} isUser={message.type === "user"}>
      {message.type === "ai" && (
        <MessageAvatar isUser={false} icon={<RobotOutlined />} />
      )}
      <MessageBubble isUser={message.type === "user"}>
        <div className="message-header">
          <span>{message.type === "user" ? user?.name || "我" : "AI助手"}</span>
          <span>{message.timestamp.toLocaleTimeString()}</span>
        </div>
        <div className="message-content">
          <Paragraph
            style={{
              margin: 0,
              color: message.type === "user" ? "#fff" : "#333",
              fontSize: "14px",
              lineHeight: "1.6",
              whiteSpace: "pre-wrap",
            }}
          >
            {message.content}
          </Paragraph>
        </div>
        {message.type === "ai" && (
          <div className="message-actions">
            <Tooltip title="复制内容">
              <button
                className="action-btn"
                onClick={() => copyMessage(message.content)}
              >
                <CopyOutlined />
              </button>
            </Tooltip>
            <Tooltip title="这个回答有帮助吗？">
              <Rate
                count={5}
                value={message.rating || 0}
                onChange={(rating) => rateMessage(message.id, rating)}
                style={{ fontSize: 12 }}
              />
            </Tooltip>
          </div>
        )}
      </MessageBubble>
      {message.type === "user" && (
        <MessageAvatar isUser={true} icon={<UserOutlined />} />
      )}
    </MessageItem>
  );

  return (
    <div
      style={{
        display: "flex",
        height: "700px",
        background: "#fff",
        borderRadius: "12px",
        overflow: "hidden",
        boxShadow: "0 4px 16px rgba(0,0,0,0.1)",
      }}
    >
      <ChatContainer style={{ flex: 1 }}>
        <ChatHeader>
          <div style={{ display: "flex", alignItems: "center", gap: "12px" }}>
            <Avatar
              size={40}
              icon={<RobotOutlined />}
              style={{
                background: "linear-gradient(135deg, #52c41a, #73d13d)",
                border: "2px solid rgba(255,255,255,0.3)",
              }}
            />
            <div>
              <div style={{ fontWeight: "bold", fontSize: "16px" }}>
                AI学习助手
              </div>
              <AIStatus>
                <div className="status-dot"></div>
                <span>在线服务中</span>
              </AIStatus>
            </div>
          </div>
          <Space>
            <Tooltip title="清空聊天">
              <Button
                type="text"
                icon={<ClearOutlined />}
                onClick={clearChat}
                style={{ color: "white" }}
              />
            </Tooltip>
          </Space>
        </ChatHeader>

        <ChatMessages>
          {messages.map(renderMessage)}

          {isTyping && (
            <MessageItem isUser={false}>
              <MessageAvatar isUser={false} icon={<RobotOutlined />} />
              <TypingIndicator>
                <Text type="secondary">AI正在思考</Text>
                <div className="dots">
                  <span></span>
                  <span></span>
                  <span></span>
                </div>
              </TypingIndicator>
            </MessageItem>
          )}
          <div ref={messagesEndRef} />
        </ChatMessages>

        <ChatInput>
          {showSuggestions && (
            <div style={{ marginBottom: "16px" }}>
              <Text
                type="secondary"
                style={{
                  fontSize: "12px",
                  marginBottom: "8px",
                  display: "block",
                }}
              >
                💡 快速开始，试试这些问题：
              </Text>
              <QuickActions>
                {quickQuestions.slice(0, 6).map((question, index) => (
                  <QuickButton
                    key={index}
                    size="small"
                    icon={question.icon}
                    onClick={() => handleQuickQuestion(question.text)}
                  >
                    {question.text}
                  </QuickButton>
                ))}
              </QuickActions>
            </div>
          )}

          <div style={{ display: "flex", gap: "12px", alignItems: "flex-end" }}>
            <TextArea
              ref={inputRef}
              value={inputValue}
              onChange={(e) => setInputValue(e.target.value)}
              onKeyPress={handleKeyPress}
              placeholder="输入您的问题，按 Enter 发送，Shift+Enter 换行..."
              autoSize={{ minRows: 1, maxRows: 4 }}
              style={{
                borderRadius: "20px",
                padding: "12px 16px",
                fontSize: "14px",
                border: "1px solid #d9d9d9",
                boxShadow: "0 2px 4px rgba(0,0,0,0.1)",
              }}
              disabled={isLoading || isTyping}
            />
            <Button
              type="primary"
              icon={<SendOutlined />}
              onClick={() => sendMessage(inputValue)}
              loading={isLoading || isTyping}
              disabled={!inputValue.trim()}
              style={{
                borderRadius: "20px",
                height: "40px",
                minWidth: "40px",
                background: "linear-gradient(135deg, #1890ff, #40a9ff)",
                border: "none",
                boxShadow: "0 2px 8px rgba(24,144,255,0.3)",
              }}
            />
          </div>
        </ChatInput>
      </ChatContainer>

      <SidePanel>
        <Tabs
          activeKey={activeTab}
          onChange={setActiveTab}
          style={{ height: "100%" }}
          tabBarStyle={{ margin: "0 16px", borderBottom: "1px solid #f0f0f0" }}
        >
          <TabPane tab="学习路径" key="paths">
            <div style={{ padding: "8px" }}>
              {learningPaths.map((path) => (
                <LearningPathCard key={path.id} size="small">
                  <div className="path-header">
                    <Text strong style={{ fontSize: "14px" }}>
                      {path.title}
                    </Text>
                    <Tag
                      className="difficulty-tag"
                      color={
                        path.difficulty === "beginner"
                          ? "green"
                          : path.difficulty === "intermediate"
                            ? "orange"
                            : "red"
                      }
                    >
                      {path.difficulty}
                    </Tag>
                  </div>
                  <Paragraph
                    style={{
                      fontSize: "12px",
                      color: "#666",
                      margin: "4px 0 8px",
                    }}
                    ellipsis={{ rows: 2 }}
                  >
                    {path.description}
                  </Paragraph>
                  <Progress
                    percent={path.progress}
                    size="small"
                    strokeColor="#1890ff"
                    style={{ marginBottom: "8px" }}
                  />
                  <div
                    style={{
                      display: "flex",
                      justifyContent: "space-between",
                      fontSize: "12px",
                      color: "#999",
                    }}
                  >
                    <span>
                      <ClockCircleOutlined /> {path.estimatedTime}
                    </span>
                    <span>
                      {path.steps.filter((s) => s.completed).length}/
                      {path.steps.length} 完成
                    </span>
                  </div>
                </LearningPathCard>
              ))}
            </div>
          </TabPane>

          <TabPane tab="学习技巧" key="tips">
            <div style={{ padding: "8px" }}>
              <Select
                value={selectedCategory}
                onChange={setSelectedCategory}
                style={{ width: "100%", marginBottom: "12px" }}
                size="small"
              >
                <Option value="all">全部技巧</Option>
                <Option value="时间管理">时间管理</Option>
                <Option value="理解方法">理解方法</Option>
                <Option value="记忆技巧">记忆技巧</Option>
              </Select>

              {filteredTips.map((tip) => (
                <Card key={tip.id} size="small" style={{ marginBottom: "8px" }}>
                  <div style={{ marginBottom: "8px" }}>
                    <div
                      style={{
                        display: "flex",
                        justifyContent: "space-between",
                        alignItems: "center",
                      }}
                    >
                      <Text strong style={{ fontSize: "13px" }}>
                        {tip.title}
                      </Text>
                      <Rate
                        disabled
                        value={Math.floor(tip.usefulness)}
                        style={{ fontSize: "10px" }}
                      />
                    </div>
                    <Tag color="blue">{tip.category}</Tag>
                  </div>
                  <Paragraph
                    style={{ fontSize: "12px", color: "#666", margin: 0 }}
                    ellipsis={{ rows: 3, expandable: true, symbol: "展开" }}
                  >
                    {tip.description}
                  </Paragraph>
                </Card>
              ))}
            </div>
          </TabPane>
        </Tabs>
      </SidePanel>
    </div>
  );
};

export default AIChat;
